package com.spring.springboot.controller;

import java.util.List;
import java.util.Locale;
import java.util.Optional;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.spring.springboot.Service.GoodService;
import com.spring.springboot.entity.GoodInfoDTO;
import com.spring.springboot.entity.GoodInfoEntity;
import com.spring.springboot.entity.GoodTypeEntity;
import com.spring.springboot.jpa.GoodJPA;
import com.spring.springboot.jpa.TypeJPA;
import com.spring.springboot.mapper.GoodInfoMapper;

/**
*@author LSY
*Time: 2018年12月12日下午2:33:44
*
*
*/
@RestController
@RequestMapping(value = "/good")
public class GoodController {

	@Autowired
	private MessageSource messageSource;
	@Autowired
	private GoodJPA goodJPA;
	
	@Autowired
	private TypeJPA typeJPA;
	
	@Autowired
	private GoodService goodService;
	
	@GetMapping(value = "/all")
	public List<GoodInfoEntity> getGoods(){
		return goodJPA.findAll();
	}
	
	@GetMapping(value = "/save")
	public GoodTypeEntity save(GoodTypeEntity entity) {
		System.out.println("========" + entity.toString());
		typeJPA.save(entity);
		return entity;
	}
	
	@RequestMapping(value ="/validator", method = RequestMethod.GET)
	public String validator(@Valid GoodTypeEntity entity, BindingResult result) {
		if(result.hasErrors()) {
			StringBuffer sb = new StringBuffer();
			Locale locale  = LocaleContextHolder.getLocale();
			List<FieldError> list = result.getFieldErrors();
			for(FieldError field : list) {
				String errorMsg = messageSource.getMessage(field, locale);
				sb.append(field.getField() + ":" + errorMsg);
			}
			return sb.toString();
		}
		
		
		return "z通过验证";
	}
	
	@GetMapping("goods")
	public List<GoodTypeEntity> getAll(){
		return goodService.findAll();
	}
	
	@GetMapping("goods/{id}")
	public GoodInfoEntity getGoodInfo(Long id) {
		return goodService.findById(id);
	}
	
	@GetMapping("del")
	public String delGood(Long id) {
		goodService.delGood(id);
		return "success";
	}
	
	@Autowired
	private GoodInfoMapper goodInfoMapper;
	@RequestMapping(value = "/detail/{id}")
    public GoodInfoDTO detail(@PathVariable("id") Long id)
    {
        //查询商品基本信息
        Optional<GoodInfoEntity> goodInfoBean = goodJPA.findById(id);
        //查询商品类型基本信息
        Optional<GoodTypeEntity> typeBean = typeJPA.findById(id);
        //返回转换dto
        return goodInfoMapper.from(goodInfoBean.get(),typeBean.get());
    }

}
